from collections import OrderedDict

from django.http import HttpResponse
# from django.shortcuts import render
from django.shortcuts import render
from django.views import View

from apps.goods.models import GoodsChannel


class IndexView(View):
    def get(self, request):
        """
        主页
        :param request:
        :return:
        """
        # 查询商品频道和分类
        categories_dict = OrderedDict()
        # print(categories_dict)
        channels = GoodsChannel.objects.order_by("group_id", "sequence")
        # print(channels)
        for channel in channels:
            group_id = channel.group_id
            # print(channel)
            if group_id not in categories_dict:
                categories_dict[group_id] = {"channels": [], "sub_cats": []}
                # print(categories_dict[group_id])
            category_1 = channel.category  # 当前频道 1级
            # print(category_1)

            categories_dict[group_id]["channels"].append({
                "id": category_1.id,
                "name": category_1.name,
                "url": channel.url
            })

            for category_2 in category_1.subs.all():
                category_2_dict = {"id": category_2.id, "name": category_2.name, "sub_cats": []}
                # print(category_2_dict)
                for category_3 in category_2.subs.all():
                    category_3_dict = {"id": category_3.id, "name": category_3.name}
                    # print(category_3_dict)
                    category_2_dict["sub_cats"].append(category_3_dict)
                categories_dict[group_id]["sub_cats"].append(category_2_dict)

        context = {
            "categories": categories_dict
        }

        return render(request, 'base_index.html', context)
